<template>
  <BaseDialog
    :visible="visible"
    :title="`选择摄像机 - ${nodeData?.name || ''}`"
    width="60%"
    :draggable="true"
    footer-type="default"
    confirm-text="确定"
    cancel-text="取消"
    :confirm-loading="loading"
    @update:visible="handleUpdateVisible"
    @confirm="handleConfirm"
    @cancel="handleCancel"
  >
    <div class="camera-list-container">
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索摄像机名称"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <!-- 摄像机列表 -->
      <div class="camera-table-container">
        <ElementTable
          ref="tableRef"
          :data="cameraList"
          :table-title="tableColumns"
          :show-pagination="true"
          :page-config="pageConfig"
          @select-change="handleSelectionChange"
        >
          <template #ptz="{ data }">
            <el-checkbox 
              v-model="data.row.ptzEnable"
              @change="handlePtzChange(data.row)"
            />
          </template>
        </ElementTable>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { ElCheckbox, ElInput, ElIcon } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import BaseDialog from '@/components/BaseDialog.vue'
import ElementTable from '@/components/ElementTable/index.vue'
import type { TreeNode } from '@/types'
import request from '@/utils/request'

// Props
interface Props {
  visible: boolean
  nodeData?: TreeNode | null
  selectedCameras?: any[]
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  nodeData: null,
  selectedCameras: () => []
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'update:selected-cameras': [value: any[]]
}>()

// 响应式数据
const tableRef = ref()
const cameraList = ref<any[]>([])
const selectedCameras = ref<any[]>([])
const searchKeyword = ref('')
const loading = ref(false)

// 分页配置
const pageConfig = ref({
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper',
  total: 0,
  background: true,
  handleSizeChange: (size: number) => {
    pageConfig.value.pageSize = size
    pageConfig.value.currentPage = 1
    loadCameraList()
  },
  handleCurrentChange: (page: number) => {
    pageConfig.value.currentPage = page
    loadCameraList()
  }
})

// 表格列配置
const tableColumns = [
  {
    type: 'selection',
    width: 50
  },
  {
    type: 'text',
    label: '摄像机名称',
    prop: 'name',
  },
  {
    type: 'text',
    label: '摄像机ID',
    prop: 'equId',
  },
  {
    type: 'custom',
    label: '是否可控云台',
    name: 'ptz',
    align: 'left'
  }
]

// 计算属性 - 现在直接使用cameraList，搜索通过后端API处理

// 处理搜索
const handleSearch = () => {
  // 搜索时重置到第一页并重新加载数据
  pageConfig.value.currentPage = 1
  loadCameraList()
}

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedCameras.value = selection
}

// 处理PTZ控制变化
const handlePtzChange = (row: any) => {
  // 更新选中摄像机列表中的PTZ状态
  const selectedCamera = selectedCameras.value.find(camera => camera.gbId === row.gbId)
  if (selectedCamera) {
    selectedCamera.ptzEnable = row.ptzEnable
  }
}

// 加载目录下的摄像机列表
const loadCameraList = async () => {
  if (!props.nodeData?.id) return
  
  try {
    loading.value = true
    const response = await request.post('/deviceController/getDeviceListByPage', {
      page: pageConfig.value.currentPage,
      pageSize: pageConfig.value.pageSize,
      keyWord: searchKeyword.value,
      menuId: props.nodeData.id,
      isContainsSubMenu: true
    })
    
    // 假设后端返回的数据结构包含 records 和 total
    if (response.data && typeof response.data === 'object') {
      cameraList.value = response.data.data
      pageConfig.value.total = response.data.total || 0
    }
  } catch (error) {
    console.error('加载摄像机列表失败:', error)
    cameraList.value = []
    pageConfig.value.total = 0
  } finally {
    loading.value = false
  }
}

// 处理对话框显示状态更新
const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

// 确定选择
const handleConfirm = () => {
  emit('update:selected-cameras', selectedCameras.value)
  handleUpdateVisible(false)
}

// 取消选择
const handleCancel = () => {
  handleUpdateVisible(false)
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newValue) => {
    if (newValue && props.nodeData) {
      // 重置分页状态
      pageConfig.value.currentPage = 1
      pageConfig.value.pageSize = 10
      searchKeyword.value = ''
      
      loadCameraList()
      // 设置已选中的摄像机
      selectedCameras.value = [...(props.selectedCameras || [])]
      
      // 更新表格选中状态
      nextTick(() => {
        if (tableRef.value) {
          tableRef.value.clearSelectionFun()
          selectedCameras.value.forEach(camera => {
            const row = cameraList.value.find(c => c.gbId === camera.gbId)
            if (row) {
              tableRef.value.toggleRowSelectionFun(row, true)
            }
          })
        }
      })
    } else {
      // 清空数据
      cameraList.value = []
      selectedCameras.value = []
      searchKeyword.value = ''
      pageConfig.value.total = 0
    }
  },
  { immediate: true }
)
</script>

<style scoped>
.camera-list-container {
  height: 100%;
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

.search-container {
  margin-bottom: 16px;
}

.camera-table-container {
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

/* 确保ElementTable内部的分页正确显示 */
:deep(.pageConfig) {
  margin-top: 16px;
  padding: 0 16px;
}
</style>
